<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\ocean;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\service\fetch\OceanFetchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class ClueProductListWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_KEY]['clue_product_list'];

    protected function configure()
    {
        // 指令配置
        $this->setName('ocean_clue_product_list_work');
        // 设置参数
        $this->setDescription('拉取巨量线索商品列表');

        // 设置参数
        $this->setHelp('php think ocean_clue_product_list_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('拉取巨量线索商品列表开始');

        $redis = Cache::store('redis')->handler();
        $st = time() + 5 * 60;
        while (time() < $st) {
            $advId = $redis->lPop(self::REDIS_TASK_KEY);
            if (! $advId) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                continue;
            }

            $this->getOutputMessage('同步[adv_id:' . $advId . ']开始');

            try {
                $res = OceanFetchService::fetchClueProductList($advId);
                if (! $res) {
                    $this->getOutputMessage('拉取巨量线索商品列表失败,adv_id:' . $advId . ',错误:' . OceanFetchService::getError(0));
                }
            } catch (\Exception $e) {
                $this->getOutputMessage($e->getMessage());
                $this->getOutputMessage($e->getFile() . '[' . $e->getLine() . ']');
                $this->getOutputMessage($e->getTraceAsString());
            }

            $this->getOutputMessage('同步[adv_id:' . $advId . ']成功');
        }
        $this->getOutputMessage('拉取巨量线索商品列表结束');
    }
}
